package com.jung.net.interceptor

import com.jung.net.NetConstantKeys
import okhttp3.Interceptor
import okhttp3.Response
import java.util.*
/**
 * @author chenshiyang
 * @time 2022/6/23 17:46
 * @name HeaderInterceptor.kt
 * @class describe
 */
class HeaderInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val builderHeader = request.headers.newBuilder()
        builderHeader.add("Content-type", "application/json; charset=utf-8")
            .add("model", "Android")
            .add("If-Modified-Since", "${Date()}")
            .add("User-Agent", System.getProperty("http.agent") ?: "unknown")
        NetConstantKeys.reqHeaderMap.let {
            it.keys.forEach { key ->
                it[key]?.let { value -> builderHeader.add(key, value) }
            }
        }
        val builderUrl = request.url.newBuilder()
        NetConstantKeys.reqUrlParamMap.let {
            it.keys.forEach { key ->
                it[key]?.let { value -> builderUrl.addQueryParameter(key, value) }
            }
        }
        val newRequest = request.newBuilder()
            .headers(builderHeader.build())
            .url(builderUrl.build())
            .build()
        return chain.proceed(newRequest)
    }
}